using System;
using Microsoft.Win32;
using System.Xml;
using System.Reflection;
using System.Diagnostics;

namespace NGNntpPlugIn
{
	
	public class ConfigException : ApplicationException
	{
		public ConfigException(string message) : base(message)
		{
		}
	}

	public class NntpConfig
	{
		private string m_keyLocation;
		private string m_name;
		private string m_email;
		private bool m_alwaysPrompt;
		private string m_lastUpdateCheck;

		public NntpConfig()
		{
			m_keyLocation = @"Software\RAI\NewsGator\Plugins\NntpPlugIn";
			m_name = "";
			m_email = "";
			m_lastUpdateCheck = "";
			m_alwaysPrompt = false;

			LoadConfig();
		}

		public string Name
		{
			get { return m_name; }
		}

		public string Email
		{
			get { return m_email; }
		}

		public bool AlwaysPromptWhenReplying
		{
			get { return m_alwaysPrompt; }
		}

		public string DisplayName
		{
			get
			{
				string output = "";

				if(m_name != "" && m_email != "")
					output = "\"" + m_name + "\" <" + m_email + ">";
				else if(m_email != "")
					output = m_email;
				else
					output = "";

				return output;
			}
		}

		public Version PluginVersion
		{
			get
			{
				return Assembly.GetExecutingAssembly().GetName().Version;
			}
		}

		public void SaveConfig(string name, string email, bool alwaysPrompt)
		{
			if(email == "")
				throw new ConfigException("Email must be configured.");
			else
			{
				SetStringValue("Name", name);
				SetStringValue("Email", email);
				SetBooleanValue("AlwaysPrompt", alwaysPrompt);
			}
		}

		public void LoadConfig()
		{
			m_name = GetStringValue("Name");
			m_email = GetStringValue("Email");
			m_alwaysPrompt = GetBooleanValue("AlwaysPrompt");
			m_lastUpdateCheck = GetStringValue("LastUpdateCheck");
		}

		private void SetStringValue(string key, string value)
		{
			// create the sub key
			RegistryKey regKey = Registry.CurrentUser.CreateSubKey(m_keyLocation);

			// set the value
			regKey.SetValue(key, value);
			regKey.Close();
		}

		private void SetBooleanValue(string key, bool value)
		{
			// create the sub key
			RegistryKey regKey = Registry.CurrentUser.CreateSubKey(m_keyLocation);

			// set the value
			regKey.SetValue(key, value.ToString());
			regKey.Close();
		}

		private string GetStringValue(string key)
		{
			// open the sub key
			RegistryKey regKey = Registry.CurrentUser.CreateSubKey(m_keyLocation);

			string value = "";

			if(regKey != null)
			{
				// retrieve the key's value
				value = regKey.GetValue(key, "").ToString();
				regKey.Close();
			}

			return value;
		}

		private bool GetBooleanValue(string key)
		{
			// open the sub key
			RegistryKey regKey = Registry.CurrentUser.CreateSubKey(m_keyLocation);

			bool value = false;

			if(regKey != null)
			{
				// retrieve the key's value
				try
				{
					// retrieve and parse the value
					value = bool.Parse(regKey.GetValue(key, "").ToString());
				}
				catch
				{
					// an exception was thrown, set it to false
					value = false;
				}
				finally
				{
					// close the registry key
					regKey.Close();
				}
			}

			return value;
		}

		public void CheckForUpdate(bool forceCheck)
		{
			XmlDocument xDoc = new XmlDocument();
			string updateVersion = "";
			string downloadUrl = "";
			string fileDesc;
			Version version;
			object[] versionNumbers = new object[5];
			string[] updateNumbers;
			string combinedUpdate = "";
			string combinedCurrent = "";
			DateTime lastUpdate = DateTime.Today.AddDays(-1);
			bool update = false;

			// retrieve the version information
			fileDesc = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileDescription;
			version = this.PluginVersion;
			versionNumbers = new object[5];
			versionNumbers[0] = fileDesc;
			versionNumbers[1] = version.Major;
			versionNumbers[2] = version.Minor;
			versionNumbers[3] = version.Build;
			versionNumbers[4] = version.Revision;

			if(m_lastUpdateCheck != "")
			{
				// the last update check was found, parse it
				lastUpdate = DateTime.Parse(m_lastUpdateCheck);
			}

			// subtract the dates
			TimeSpan ts = lastUpdate.Subtract(DateTime.Today);

			if(ts.Days < 0 || forceCheck)
			{

				try
				{
					// load the xml document
					xDoc.Load("http://www.eworldui.net/files/nntpplugin/nntpversion.xml");

					// get the NntpPlugin element
					XmlNode nntpEl = xDoc.SelectSingleNode("/Update/NntpPlugin");

					if(nntpEl != null)
					{
						// retrieve the current version and download url
						foreach(XmlElement el in nntpEl.ChildNodes)
						{
							if(el.Name == "Version")
								updateVersion = el.InnerText;
							if(el.Name == "UpdateUrl")
								downloadUrl = el.InnerText;
						}

						// split the update numbers
						updateNumbers = updateVersion.Split('.');

						// combine the update numbers
						combinedUpdate = updateNumbers[0] + updateNumbers[1] + updateNumbers[2] + updateNumbers[3];
					
						// combine the current numbers
						combinedCurrent = versionNumbers[1].ToString() + versionNumbers[2].ToString() + versionNumbers[3].ToString() + versionNumbers[4].ToString();

						if(int.Parse(combinedUpdate) > int.Parse(combinedCurrent))
						{
							// user needs to update
							if(System.Windows.Forms.MessageBox.Show("There is a newer version of the NNTP Plugin for NewsGator. Would you like to download it now?", "New Update Available", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
							{
								// the user has chosen to update
								System.Diagnostics.Process.Start(downloadUrl);
							}
						}
						else if(forceCheck)
						{
							// there is no update
							System.Windows.Forms.MessageBox.Show("There are no updates available at this time.", "No Updates Available", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
						}

						// update the registry to not check anymore today
						m_lastUpdateCheck = DateTime.Today.ToShortDateString();
						SetStringValue("LastUpdateCheck", m_lastUpdateCheck);
					}
				}
				catch (Exception ex)
				{
					// supress the message
					//MessageBox.Show(ex.Message);
				}
			}
		}

	}
}
